#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
import time
import shutil

def clear_folder(folder_path):
    """清空指定文件夹中的所有文件"""
    if os.path.exists(folder_path):
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print(f'删除 {file_path} 时出错: {e}')
        print(f'已清空文件夹: {folder_path}')

def run_script(script_path, script_name):
    """
    运行指定的Python脚本
    """
    # print(f"\n{'='*50}")
    # print(f"开始运行: {script_name}")
    # print(f"{'='*50}")
    
    try:
        # 使用subprocess运行脚本
        result = subprocess.run([sys.executable, script_path], 
                              capture_output=True, 
                              text=True, 
                              encoding='utf-8')
        
        # 输出脚本的标准输出
        if result.stdout:
            print(result.stdout)
        
        # 如果有错误输出，也显示出来
        if result.stderr:
            print(f"警告/错误信息: {result.stderr}")
        
        # 检查返回码
        if result.returncode == 0:
            # print(f"✓ {script_name} 执行成功")
            return True
        else:
            print(f"✗ {script_name} 执行失败，返回码: {result.returncode}")
            return False
            
    except Exception as e:
        print(f"✗ 运行 {script_name} 时发生异常: {e}")
        return False

def main():
    """
    主函数：依次运行三个处理脚本
    """
    # 清空输出文件夹
    current_dir = os.path.dirname(os.path.abspath(__file__))
    html_folder = os.path.join(current_dir, 'html')
    xml_folder = os.path.join(current_dir, 'xml')
    csv_folder = os.path.join(current_dir, 'csv')
    
    clear_folder(html_folder)
    clear_folder(xml_folder)
    clear_folder(csv_folder)
    
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 定义要运行的脚本列表（按顺序）
    scripts = [
        {
            'path': os.path.join(current_dir, 'A_doc_to_html.py'),
            'name': 'A_doc_to_html.py (Word → HTML)'
        },
        {
            'path': os.path.join(current_dir, 'B_html_to_xml.py'),
            'name': 'B_html_to_xml.py (HTML → XML)'
        },
        {
            'path': os.path.join(current_dir, 'C_xml_to_csv.py'),
            'name': 'C_xml_to_csv.py (XML → CSV)'
        }
    ]
    
    # 检查所有脚本文件是否存在
    for script in scripts:
        if not os.path.exists(script['path']):
            print(f"✗ 错误: 找不到脚本文件 {script['path']}")
            return False
    
    # 记录开始时间
    start_time = time.time()
    success_count = 0
    
    # 依次运行每个脚本
    for i, script in enumerate(scripts, 1):
        print(f"\n[{i}/{len(scripts)}] 准备运行: {script['name']}")
        
        if run_script(script['path'], script['name']):
            success_count += 1
            print(f"第 {i} 步完成")
        else:
            print(f"第 {i} 步失败，停止后续处理")
            break
        
        # 在脚本之间添加短暂延迟
        if i < len(scripts):
            time.sleep(1)
    
    # 计算总耗时
    end_time = time.time()
    total_time = end_time - start_time
    
    # 输出最终结果
    # print(f"\n{'='*60}")
    # print("处理完成！")
    # print(f"{'='*60}")
    # print(f"成功执行: {success_count}/{len(scripts)} 个脚本")
    print(f"总耗时: {total_time:.2f} 秒")
    
    if success_count == len(scripts):
        print("\n输出文件位置:")
        print("- HTML文件: A_segmenter/html/")
        print("- XML文件: A_segmenter/xml/")
        print("- CSV文件: A_segmenter/csv/")
        return True
    else:
        print(f"\n处理过程中有 {len(scripts) - success_count} 个步骤失败")
        return False

if __name__ == '__main__':
    try:
        success = main()
        # 静默退出，不输出任何提示
        if not success:
            sys.exit(1)
    except KeyboardInterrupt:
        sys.exit(1)
    except Exception as e:
        sys.exit(1)